package com.woniu.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.car.dto.CouponUseDto;
import com.woniu.car.entity.TCouponLogs;
import com.woniu.car.entity.TCouponReceive;
import com.woniu.car.exception.StatisticsException;
import com.woniu.car.mapper.TCouponReceiveMapper;
import com.woniu.car.properties.StatisticsProperties;
import com.woniu.car.service.TCouponLogsService;
import com.woniu.car.service.TCouponReceiveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuyanzu
 * @since 2021-06-22
 */
@Service
public class TCouponReceiveServiceImpl extends ServiceImpl<TCouponReceiveMapper, TCouponReceive> implements TCouponReceiveService {
    @Autowired
    TCouponLogsService logsService;
    @Autowired
    TCouponReceiveService receiveService;
    @Override
    public List<TCouponReceive> searchUserCoupon(Integer userId) throws Exception {
        List<TCouponReceive> list = list(new QueryWrapper<TCouponReceive>().eq("user_id", userId));
        System.out.println(userId);
        if(userId<0)
            throw new StatisticsException(StatisticsProperties.NOID);
        if (list.size()==0)
            throw new StatisticsException(StatisticsProperties.NOUSERCOUPON);
        return list;
    }

    @Override
    public boolean deleteUserCoupon(Integer couponReceiveId) throws Exception {
        if(couponReceiveId<0||null==couponReceiveId)
            throw new StatisticsException(StatisticsProperties.ERRORPARAMETER);
        boolean b = removeById(couponReceiveId);
        if(!b)
            throw new StatisticsException(StatisticsProperties.DELETECOUPONFAIL);
        return b;
    }
    @Transactional
    @Override
    public CouponUseDto couponUseCoupon(Integer couponReceiveId) throws Exception {
        if(couponReceiveId<0||null==couponReceiveId)
            throw new StatisticsException(StatisticsProperties.ERRORPARAMETER);
        TCouponReceive receive = getOne(new QueryWrapper<TCouponReceive>().eq("coupon_receive_id", couponReceiveId));
        if(null==receive)
            throw new StatisticsException(StatisticsProperties.NOUSERCOUPON);
       
        if("1".equals(receive.getStatus()))
            throw new StatisticsException("优惠券已被使用");
        TCouponLogs logs = new TCouponLogs();
        BeanUtils.copyProperties(receive,logs);
        logsService.insertCouponLogs(logs);
        CouponUseDto dto = new CouponUseDto();
        BeanUtils.copyProperties(receive,dto);
        receive.setStatus("1");
        receiveService.updateById(receive);
        
        return dto;
    }
}
